#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.shortcuts import *
from django.http import *
from django.template import RequestContext

from utils import *
import os
import datetime
import random
import markdown
import codecs
import html2text
from PIL import Image

from forms import UploadFileForm
from settings import MEDIA_ROOT
from researchSNS.SNS.models import *
from researchSNS.Group.models import *
from researchSNS.QA.models import *

#一般的页面开始都要验证是否已经登录，若否则跳转到LOGIN页面
#一些平常的页面，如群组首页等，游客也有浏览权限，就不去验证

def get_username(request):

    user_id = request.session.get('user_id')
    if user_id:
        try:
            user_id = int(user_id)
            user = User.objects.get(id = user_id)
            return user.name
        except:
            return '游客'
    return '游客'


def comp( a, b ):
    if isinstance(a, tuple):
        a = a[0].question_datetime
    else:
        a = a.post_datetime
    if isinstance(b, tuple):
        b = b[0].question_datetime
    else:
        b = b.post_datetime
    if a < b:
        return 1
    else:
        return -1


def another_comp( a, b ):
    if isinstance(a, Post):
        a = a.post_datetime
    else:
        a = a.question_datetime
    if isinstance(b, Post):
        b = b.post_datetime
    else:
        b = b.question_datetime
    if a < b:
        return 1
    else:
        return -1


def create_page( page_index , posts_or_questions , name, stick_posts):
    
    render_result = {}

    posts_or_questions = list(posts_or_questions)
    total_page = len(posts_or_questions) / POSTS_PER_PAGE
    if len(posts_or_questions) > total_page * POSTS_PER_PAGE:
        total_page += 1
    if total_page < 1:
        total_page = 1
    if page_index > total_page:
        page_index = total_page

    #The first page shows all the stick_posts

    if stick_posts:
        render_result[name] = list(stick_posts)
        render_result[name].extend( posts_or_questions[page_index*POSTS_PER_PAGE - POSTS_PER_PAGE : page_index*POSTS_PER_PAGE] )
    else:
        render_result[name] = posts_or_questions[page_index*POSTS_PER_PAGE - POSTS_PER_PAGE : page_index*POSTS_PER_PAGE]
    
    render_result['current_page'] = page_index    
    if len(posts_or_questions) <= POSTS_PER_PAGE and page_index == 1:
        render_result['show'] = False
    else:
        render_result['show'] = True
     
    if total_page <= 5:
        render_result['page_list'] = range(1, total_page+1)
    else:
        if page_index < 3:
            render_result['page_list'] = range(1, 6)
        elif page_index > total_page-3:
            render_result['page_list'] = range(total_page-4, total_page+1)
        else:
            render_result['page_list'] = range(page_index-2, page_index+3)

    render_result['final_page'] = total_page
    render_result['last_page'] = page_index-1
    render_result['next_page'] = page_index+1
    try:
        render_result['page_list_final'] = render_result['page_list'][-1]
    except:
        render_result['page_list_final'] = ''
    render_result['suffix'] = name
    
    return render_result


def show_topics(request, page_index=1):

    render_result = {}
    user_id = request.session.get('user_id')
    #username = ''
    if not user_id:
        return HttpResponseRedirect('/group/all_groups/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        return HttpResponseRedirect('/group/all_groups/')
    groups = user.groups.all()
    posts = Post.objects.filter(group__in = groups, stick = False).order_by('-post_datetime')
    topics = []
    questions = []
    for group in groups: 
        for question in group.questions.all():
            if not question in questions:  
                topics.append( (question, group) )
                questions.append( question )
    topics.extend( list(posts) )

    topics.sort(cmp=comp)
    
    try:
        page_index = int(page_index)
    except:
        page_index = 1
     
    if page_index == 1:
        stick_posts = Post.objects.filter(group__in = groups, stick = True).order_by('-post_datetime')
        render_result = create_page(page_index, topics, 'topics', stick_posts )
    else:
        render_result = create_page(page_index, topics, 'topics', '' )
        
    render_result['groups'] = groups[:8]
    render_result['username'] = get_username(request)
     
    return render_to_response('topics.html', render_result)


def show_posts(request, page_index=1):

    render_result = {}
    #request.session['user_id'] = '1'    
    user_id = request.session.get('user_id')
    #username = ''
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        return HttpResponseForbidden();
    groups = user.groups.all()
    posts = Post.objects.filter(group__in = groups, stick = False).order_by('-post_datetime')

    try:
        page_index = int(page_index)
    except:
        page_index = 1
    
    if page_index == 1:
        stick_posts = Post.objects.filter(group__in = groups, stick = True).order_by('-post_datetime')
        render_result = create_page( page_index, posts, 'posts', stick_posts )
    else:
        render_result = create_page( page_index, posts, 'posts', '')
    render_result['username'] = get_username(request)
    
    return render_to_response('posts.html', render_result)


def show_questions(request, page_index=1):

    render_result = {}
    #request.session['user_id'] = 1
    user_id = request.session.get('user_id')
    #username = ''
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        return HttpResponseForbidden()
    groups = user.groups.all()
    questions = []
    qs = []
    for group in groups:
        for question in group.questions.all():
            if not question in qs:
                qs.append(question)
                questions.append((question, group))

    try:
        page_index = int(page_index)
    except:
        page_index = 1
    render_result = create_page( page_index , questions, 'questions', '')
    render_result['username'] = get_username(request)

    return render_to_response('questions.html', render_result)


def my_topics(request, page_index=1):

    render_result = {}
    user_id = request.session.get('user_id');
    #username = ''
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        return HttpResponseForbidden()
    my_posts = Post.objects.filter(poster = user, stick = False)
    my_questions = Question.objects.filter(questioner = user )
    my_topics = list(my_posts) + list(my_questions)
    my_topics.sort( cmp=another_comp )

    try:
        page_index = int(page_index)
    except:
        page_index = 1

    if page_index == 1:
        stick_posts = Post.objects.filter(poster = user, stick = True)
        render_result = create_page( page_index, my_topics, 'my_topics', stick_posts )
    else:
        render_result = create_page( page_index, my_topics, 'my_topics', '' )
    render_result['username'] = get_username(request)

    return render_to_response('my_topics.html', render_result )


def my_replied_topics(request, page_index=1):

    render_result = {}
    user_id = request.session.get('user_id')
    #username = ''
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        return HttpResponseForbidden()
    my_replies = Reply.objects.filter(replier = user)
    posts = []
    stick_posts = []
    for my_reply in my_replies:
        if not my_reply.post in stick_posts and not my_reply.post in posts: 
            if my_reply.post.stick:
                stick_posts.append(my_reply.post)
            else:
                posts.append(my_reply.post)

    my_answers = Answer.objects.filter(answerer = user)
    questions = []
    for my_answer in my_answers:
        questions.append(my_answer.question)
    my_replied_topics = list(posts) + list(questions)
    my_replied_topics.sort( cmp=another_comp )

    try:
        page_index = int(page_index)
    except:
        page_index = 1

    if page_index == 1:
        render_result = create_page(page_index, my_replied_topics, 'my_replied_topics', stick_posts )
    else:
        render_result = create_page(page_index, my_replied_topics, 'my_replied_topics', '')

    render_result['username'] = get_username(request)
    return render_to_response('my_replied_topics.html', render_result )


def add_reply(request, post_id, page_index):

    user_id = request.session.get('user_id')
    
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
    except:
        return HttpResponseForbidden()    
    try:
        post_id = int(post_id)
        post = Post.objects.get(id = post_id)
    except:
        return HttpResponseRedirect('/group/gr/' + str(group.id) )    
    group = post.group
    if not user in group.members.all():
        return HttpResponseRedirect('/group/post/' + str(post_id) )

    if request.method == 'POST':
        content = request.POST.get('content', '')
        content = markdown.markdown(content)
        if content != '':
            replies = list( Reply.objects.filter(post = post).order_by('floor_num') )
            try:
                floor = replies[-1].floor_num + 1
            except:
                floor = 1
            reply = Reply(post = post, content = content, replier = user, floor_num = floor )
            reply.save()
	    Post.objects.filter(id = post_id).update(replied_count = post.replied_count+1)    
    try:
        page_index = int(page_index) + 1
    except:
        return HttpResponseRedirect('/group/post/' + str(post_id) )

    return HttpResponseRedirect('/group/post/' + str(post_id) + '/page/'+ str(page_index) +'/#reply' )


def deal_post(request, post_id, opr, reply_id=1, page_index=1):

    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
    except:
        return HttpResponseForbidden()
    try:
        post_id = int(post_id)
        post = Post.objects.get(id = post_id)
    except:
        return HttpResponseRedirect('/group/topicts/')
    group = post.group
    if not user in group.administrators.all():
        return HttpResponseForbidden()

    if opr == 'elite':
        Post.objects.filter(id = post_id).update(elite = True)
    elif opr == 'stick':
        Post.objects.filter(id = post_id).update(stick = True)
    elif opr == 'cancel_elite':
        Post.objects.filter(id = post_id).update(elite = False)
    elif opr == 'cancel_stick':
        Post.objects.filter(id = post_id).update(stick = False)
    elif opr == 'delete':
        replies = Reply.objects.filter(post = post)
        if replies:
            replies.delete()
        post.delete()
        return HttpResponseRedirect('/group/gr/' + str(group.id))
    elif opr == 'delete_reply':
        try:
            reply_id = int(reply_id)
            reply = Reply.objects.get(id = reply_id)
        except:
            return HttpResponseRedirect('/group/post/' + str(post_id))
        reply.delete()
        return HttpResponseRedirect('/group/post/' + str(post_id) + '/page/' + str(page_index))

    return HttpResponseRedirect('/group/post/' + str(post_id))
    

def show_post_one(request, post_id, page_index = 1, opr= '', reply_id = 1):

    render_result = {}
    user_id = request.session.get('user_id')
    #username = ''
    if not user_id:
        user_id = None
        #return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        user = None
        #return HttpResponseForbidden()
    try:
        post = Post.objects.get(id = post_id)
    except:
        return HttpResponseRedirect('/group/topics/')
    replies = post.reply_set.all().order_by('floor_num')
    try:
        page_index = int(page_index)
    except:
        page_index = 1
    group = post.group
    is_admin = (user in group.administrators.all() )
    is_member = (user in group.members.all() )
        
    render_result = create_page(page_index, replies, 'replies', '')
    render_result['is_host'] = (user == post.poster)
    render_result['group'] = group
    render_result['is_admin'] = is_admin;
    render_result['is_member'] = is_member;
    render_result['new_posts'] = group.post_set.all().order_by('-post_datetime')[:10]
    render_result['post'] = post
    if post.attachment:
        the_time = str(post.post_datetime)
        year = the_time[:4]
        month = the_time[5:7]
        day = the_time[8:10]
        render_result['attach_url'] = '%s/%s/%s/%s' % (year, month, day, post.attachment)
    else:
        render_result['attach_url'] = ''
    render_result['suffix'] = 'post/' + str(post.id)
    floors = ('沙发', '板凳', '地毯', '地板', '地下室', '地基', '地壳', '地幔', '地核')
    render_result['FLOORS'] = enumerate(floors)
    render_result['username'] = get_username(request)
    
    return render_to_response('post_one.html', render_result, context_instance=RequestContext(request) )


def join_group(request, group_id):

    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id )
    except:
        return HttpResponseForbidden()
    try:
        group_id = int(group_id)
        group = Group.objects.get(id = group_id)
    except:
        return HttpResponseForbidden()

    if not user in group.members.all():
        if group.join_type == 'R':
            memberapply = MemberApply.objects.filter(member = user, group = group)
            if not memberapply:
                memberapply = MemberApply(member = user, group = group)
                memberapply.save()
        else:
            membership = MemberShip(member = user, group = group)
            membership.save()

    return HttpResponseRedirect('/group/gr/' + str(group_id) )


def exit_group(request, group_id):
    
    user_id = request.session.get('user_id')
    if not user_id:
       return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
    except:
        return HttpResponseForbidden()
    try:
        group_id = int(group_id)
        group = Group.objects.get(id = group_id)
    except:
        return HttpResponseForbidden()

    if user in group.members.all():
        membership = MemberShip.objects.filter(member = user, group = group)
        if membership:
            membership.delete()

    return HttpResponseRedirect('/group/gr/' + str(group_id))


def show_group(request, id_or_domainname, page_index = 1, join_or_exit=''):

    render_result = {}
    user_id = request.session.get('user_id')
    #username = ''
    
    if not user_id:
        user_id = None
        #return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        user = None
        #return HttpResponseForbidden()
        
    try:
        group_id = int(id_or_domainname, 10)
        group = get_group_by_id(group_id)
    except:
        group_domainname = id_or_domainname
        group = get_group_by_domainname(group_domainname)
    if group == None:
        return HttpResponseNotFound()
    try:
        page_index = int(page_index)
    except:
        page_index = 1

    posts = group.post_set.filter(stick = False).order_by('-post_datetime')
    if page_index == 1:
        stick_posts = group.post_set.filter(stick = True).order_by('-post_datetime')
        render_result = create_page( page_index, posts, 'posts', stick_posts )
    else:
        render_result = create_page( page_index, posts, 'posts', '' )

    group_applies = FriendGroupApply.objects.filter( group_to = group )
    member_applies = MemberApply.objects.filter(group = group)
    apply_number = len(group_applies) + len(member_applies)
    
    render_result['apply_number'] = apply_number   
    friend_groups = group.friend_groups.all()[:4]
    render_result['friend_groups'] = friend_groups
    memberships = MemberShip.objects.filter(group = group).order_by('-join_datetime')
    render_result['memberships'] = memberships
    render_result['new_memberships'] = memberships[:8]
    render_result['group'] = group
    render_result['description'] = markdown.markdown(group.description)
    is_member = (user in group.members.all())
    render_result['is_member'] = is_member
    render_result['is_admin'] = (user in group.administrators.all() )
    render_result['suffix'] = 'gr/' + str(group.id)
    render_result['group_applies'] = group_applies
    render_result['member_applies'] = member_applies
    render_result['username'] = get_username(request)

    memberapply = MemberApply.objects.filter(group = group, member = user)
    if memberapply:
        is_apply = True
    else:
        is_apply = False
    render_result['is_apply'] = is_apply

    return render_to_response('show_group.html', render_result)


def show_members(request, group_id, page_index=1):

    render_result = {}

    group = Group.objects.get(id = group_id)
    members = group.members.all()
    administrators = group.administrators.all()
    try:
        page_index = int(page_index)
    except:
        page_index = 1
    
    render_result = create_page(page_index, members, 'members', '' )
    render_result['suffix'] = 'members/' + str(group.id)
    render_result['group'] = group
    if page_index == 1:
        render_result['administrators'] = administrators
    render_result['username'] = get_username(request)
    
    return render_to_response('members.html', render_result )


def new_topic(request, group_id = 1):

    render_result = {}
    #username = ''
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        return HttpResponseForbidden()
    try:
        group_id = int(group_id)
        group = Group.objects.get(id = group_id)
    except:
        return HttpResponseForbidden()
    if not user in group.members.all():
        return HttpResponseForbidden()

    error_title = False
    error_text = False
    error_title_toolong = False
    content = ''
    title = ''
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        f = ''
        if form.is_valid():
            try:
                f = request.FILES['myfile']
            except:
                f = ''
        if f:
            attachment = f.name
        else:
            attachment = ''
            
        title = request.POST.get('title', '')
        if title == '':
            error_title = True
        elif len(title) > 40:
            error_title_toolong = True            
        text = request.POST.get('text', '')
        content = text
        text = markdown.markdown(text) 
        if text == '':
            error_text = True

        if not error_title and not error_text and not error_title_toolong:
            post = Post(title=title, content=text, attachment=attachment, group=group, poster=user)
            post.save()                      
            if f and attachment and f.size < 20000000:  # 文件最大20MB
                attachment = handle_upload_file(f, attachment, post.post_datetime)
                Post.objects.filter(id = post.id).update(attachment = attachment)
            else:
                Post.objects.filter(id = post.id).update(attachment = '')
                
            return HttpResponseRedirect('/group/post/' + str(post.id))
    else:
        form = UploadFileForm()

    render_result['error_title'] = error_title
    render_result['error_text'] = error_text
    render_result['error_title_toolong'] = error_title_toolong
    render_result['title'] = title
    render_result['content'] = content
    render_result['user'] = user
    render_result['group'] = group
    render_result['is_admin'] = user in group.administrators.all()
    render_result['username'] = get_username(request)
    render_result['form'] = form
    
    return render_to_response('new_topic.html', render_result )

   
def handle_upload_file(fp, name, the_time):
    
    path = MEDIA_ROOT + 'upload_file/'
        
    '2011-10-26'
    the_time = str(the_time)
    year = the_time[:4]
    month = the_time[5:7]
    day = the_time[8:10]
    path = path + '%s/%s/%s/' % (year, month, day)
    if not os.path.isdir(path):
        os.makedirs(path)
    filename = path + name
    while os.path.isfile(filename):
        name = os.path.basename(filename)
        fn, fext = os.path.splitext(name)
        name = fn + '_' + fext
        filename = path + name
    destination = open(filename, 'wb+')
    for ch in fp.chunks():
        destination.write(ch)
    destination.close()
    
    print name
    return name


def new_group(request):

    error_flag = {
        'name': False,
        'name_exist': False,
        'agreement': False,
        'suffix': False,
    }        
    error_messages = {
        'name': u'群组名称不能为空',
        'name_exist': u'该群组名已经被使用',
        'agreement': u'请选择',
        'suffix': u'该域名已经被使用',
    }

    render_result = {}
    #username = ''
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        return HttpResponseForbidden()

    if request.method == 'POST':
        error = False
        agreement = request.POST.get('grp_agreement', '')
        if not agreement:
            error = True
            error_flag['agreement'] = True

        name = request.POST.get('grp_name', '')
        if name == '':
            error = True
            error_flag['name'] = True
        elif len(name)>10:
            error = True
            error_flag['name'] = True
            error_messages['name'] = u'群组名不能多于10字符'
        else:
            grp = Group.objects.filter(name = name)
            if grp:
                error = True
                error_flag['name_exist'] = True
        intro = request.POST.get('grp_intro', '')
        content = intro
        intro = markdown.markdown( intro )
        tags = request.POST.get('grp_tags', '')
        join_type = request.POST.get('grp_join_type', 'A')
        suffix = request.POST.get('grp_suffix', '')
        if suffix != '':
            gr = Group.objects.filter(domainname_suffix = suffix)
            if gr:
                error = True
                error_flag['suffix'] = True
            
        if error:
            render_result['name'] = name
            render_result['content'] = content
            render_result['tags'] = tags
            render_result['suffix'] = suffix
            render_result['error_messages'] = error_messages
            render_result['error_flag'] = error_flag
            return render_to_response('new_group.html', render_result )
        group = Group(name=name, description=intro, member_nickname=name, logo='/group_image/group.jpg', join_type = join_type)
        group.save()
        group.administrators.add(user)
        group.save()
        membership = MemberShip(member=user, group=group, credit=100)
        membership.save()
        return HttpResponseRedirect('/group/gr/'+str(group.id) )        
    render_result['username'] = get_username(request)
    return render_to_response('new_group.html', render_result )


def recommend_groups(request):

    render_result = {}
    #username = ''
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
        #username = user.name
    except:
        return HttpResponseForbidden()
    groups = Group.objects.all().order_by('-create_datetime')
    new_group_list = groups[:4]
    new_groups = []
    for g in new_group_list:
        name, ext = os.path.splitext(g.logo.name)
        large_logo = name + '_large' + ext
        new_groups.append((g, large_logo))
        
    group_num = len(groups)
    #id_list = range(1, group_num+1)
    groups = list( groups )
    random.shuffle( groups )
    random_groups = groups[:10]

    render_result['new_groups'] = new_groups
    render_result['random_groups'] = random_groups
    render_result['username'] = get_username(request)
    
    return render_to_response('recommend_groups.html', render_result )

def all_groups(request, page_index = 1):

    render_result = {}
    try:
        page_index = int(page_index)
    except:
        page_index = 1

    groups = Group.objects.all()
    render_result = create_page(page_index, groups, 'all_groups', '')
    render_result['username'] = get_username(request)

    return render_to_response('all_groups.html', render_result )


def my_groups(request, page_index=1):

    render_result = {}
    #username = ''
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id )
    except:
        return HttpResponseForbidden()
    try:
        page_index = int(page_index)
    except:
        page_index = 1

    my_groups = user.groups.all()
    render_result=  create_page(page_index, my_groups, 'my_groups', '')
    render_result['username'] = get_username(request)

    return render_to_response('my_groups.html', render_result)


def update_group(request, group_id):

    render_result = {}

    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user = User.objects.get(id = user_id )
    except:
        return HttpResponseForbidden()
    try:
        group_id = int(group_id)
        group = Group.objects.get(id = group_id)
    except:
        return HttpResponseForbidden()
    admins = group.administrators.all()
    if not user in admins:
        return HttpResponseForbidden()
    
    render_result['group'] = group
    render_result['intro'] = html2text.html2text( group.description )
    #render_result['tags'] = group.tags
    render_result['logo'] = group.logo
    render_result['join_type'] = group.join_type

    if request.method == 'POST':
        #logo = request.POST.get('logo', '')
        #if logo:
        #    Group.objects.filter(id = group_id).update(logo = logo)
        logo = request.FILES.get('logo', None)
        logo_path = group.logo
        if logo and logo.name:
            exts = ['.gif', '.jpg', '.jpeg', '.png', '.bmp']
            ff, file_ext = os.path.splitext(logo.name)
            if file_ext in exts and logo.size < 4000000:  # 图片最大4MB
                name = str(group_id) + '_' + logo.name
                logo_path = save_group_logo(logo, name)
            
        intro = request.POST.get('grp_intro', '')
        intro = markdown.markdown(intro)
        join_type = request.POST.get('grp_join_type', 'A')
        Group.objects.filter(id = group_id).update(logo = logo_path, description = intro, join_type = join_type)
        
        return HttpResponseRedirect('/group/gr/'+ str(group.id))
    render_result['username'] = get_username(request)
    
    return render_to_response('update_group.html', render_result)

def save_group_logo(logo, name):
    
    exts = ['.gif', '.jpg', '.jpeg', '.png', '.bmp']
    f, fext = os.path.splitext(name)
    name_large = f + '_large' + fext 
    if not fext in exts or logo.size > 1000000:
        return ''
    image = logo.read()
    import StringIO
    image = StringIO.StringIO(image)
    img = Image.open(image)
    # 切出正方形图片
    if img.size[0]>img.size[1]:
        offset=int(img.size[0]-img.size[1])/2
        img=img.transform((img.size[1],img.size[1]), Image.EXTENT, \
                          (offset,0,int(img.size[0]-offset),img.size[1]))
    else:
        offset=int(img.size[1]-img.size[0])/2
        img=img.transform((img.size[0],img.size[0]), Image.EXTENT, \
                          (0,offset,img.size[0],(img.size[1]-offset)))
    year = time.strftime("%Y")
    month = time.strftime("%m")
    day = time.strftime("%d") 
    path = MEDIA_ROOT + 'group_image/%s/%s/%s/' % (year, month, day)
    if not os.path.isdir(path):
        os.makedirs(path)
       
    img.thumbnail((100, 100))    
    img.save(path + name_large)    

    img.thumbnail((48, 48))
    img.save(path + name)

    return '/group_image/%s/%s/%s/%s' % (year, month, day, name)


def friend_groups(request, group_id, page_index = 1):

    render_result = {}
    
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id )
    except:
        return HttpResponseForbidden()
    try:
        group_id = int(group_id)
        group = Group.objects.get(id = group_id)
    except:
        return HttpResponseForbidden()
    
    admins = group.administrators.all()
    if not user in admins:
        return HttpResponseForbidden()
        
    try:
        page_index = int(page_index)
    except:
        page_index = 1

    friend_groups = group.friend_groups.all()
    all_groups = Group.objects.all()
    applies = FriendGroupApply.objects.filter( group_from = group)
    apply_groups = []
    for a in applies:
        apply_groups.append(a.group_to)
    #groups = Group.objects.exclude( friend_groups )
    groups = []
    for g in all_groups:
       if not g in friend_groups and not g in apply_groups and not g == group:
           groups.append( g )
            
    render_result = create_page(page_index, groups, 'groups', '')

    render_result['my_group'] = group
    render_result['description'] = html2text.html2text( group.description )
    render_result['apply_groups'] = apply_groups
    render_result['friend_groups'] = friend_groups
    render_result['suffix'] = 'friend_groups/' + str(group.id)
    render_result['username'] = get_username(request)

    return render_to_response('friend_groups.html', render_result)


def apply_friend_group(request, group_id, friend_group_id, page_index):

    user_id = request.session.get('user_id')
    if not user_id:
        return HttpRequestRedirect('/login/')
    
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
    except:
        return HttpResponseForbidden()
    
    try:
        group_id = int(group_id)
        friend_group_id = int(friend_group_id)
        group = Group.objects.get(id = group_id)
        friend_group = Group.objects.get(id = friend_group_id)
    except:
        return HttpResonseRedirect('/group/topics/')

    try:
        page_index = int(page_index)
    except:
        page_index = 1

    if not friend_group in group.friend_groups.all():
        #group.friend_groups.add(friend_group)
        #group.save()
        friend_group_apply = FriendGroupApply.objects.filter(group_from = group, group_to = friend_group)
        if not friend_group_apply:
            friend_group_apply = FriendGroupApply(group_from = group, group_to = friend_group)
            friend_group_apply.save()

    return HttpResponseRedirect('/group/friend_groups/' + str(group.id) +'/page/' + str(page_index) )

def accept_member(request, group_id, member_id, opr):

    user_id = request.session.get('user_id')
    if not user_id:
        return HttpRequestRedirect('/login/')
    
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
    except:
        return HttpResponseForbidden()
    
    try:
        group_id = int(group_id)
        member_id = int(member_id)
        group = Group.objects.get(id = group_id)
        member = User.objects.get(id = member_id)
    except:
        return HttpResonseRedirect('/group/topics/')

    apply_ = MemberApply.objects.filter(group = group, member = member)
    if apply_:
        apply_.delete()
        if opr == 'accept':
            if not member in group.members.all():
                membership = MemberShip(group = group, member = member)
                membership.save()

    return HttpResponseRedirect('/group/group_requests/' + str(group.id))

def accept_friend_group(request, group_id, friend_group_id, opr):

    user_id = request.session.get('user_id')
    if not user_id:
        return HttpRequestRedirect('/login/')
    
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
    except:
        return HttpResponseForbidden()
    
    try:
        group_id = int(group_id)
        friend_group_id = int(friend_group_id)
        group = Group.objects.get(id = group_id)
        friend_group = Group.objects.get(id = friend_group_id)
    except:
        return HttpResonseRedirect('/group/topics/')

    apply_1 = FriendGroupApply.objects.filter(group_to = group, group_from = friend_group)
    if apply_1:
        apply_1.delete()
        apply_2 = FriendGroupApply.objects.filter(group_to = friend_group, group_from = group)
        if apply_2:
            apply_2.delete()
        if opr == 'accept':
            if not friend_group in group.friend_groups.all():
                group.friend_groups.add(friend_group)
                group.save()

    return HttpResponseRedirect('/group/group_requests/' + str(group.id))

def cancel_friend_group(request, group_id, friend_group_id ):

    user_id = request.session.get('user_id')
    if not user_id:
        return HttpRequestRedirect('/login/')
    
    try:
        user = User.objects.get(id = user_id)
    except:
        return HttpResponseForbidden()
    
    try:
        group_id = int(group_id)
        friend_group_id = int(friend_group_id)
        group = Group.objects.get(id = group_id)
        friend_group = Group.objects.get(id = friend_group_id)
    except:
        return HttpResonseRedirect('/group/topics/')

    if friend_group in group.friend_groups.all():
        group.friend_groups.remove( friend_group )

    return HttpResponseRedirect('/group/friend_groups/' + str(group.id) )

def deal_requests(request, group_id):

    render_result = {}
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user_id = int(user_id)
        user = User.objects.get(id = user_id)
    except:
        return HttpResponseForbidden()
    try:
        group_id = int(group_id)
        group = Group.objects.get(id = group_id)
    except:
        return HttpResponseRedirect('/group/topics/')
    if not user in group.administrators.all():
        return HttpResponseRedirect('/group/gr/' + str(group_id) )

    group_applies = FriendGroupApply.objects.filter(group_to = group)
    member_applies = MemberApply.objects.filter(group = group)
    render_result['group_applies'] = group_applies
    render_result['member_applies'] = member_applies
    render_result['group'] = group
    render_result['username'] = get_username(request)

    return render_to_response('group_requests.html', render_result)


def update_topic(request, post_id):

    render_result = {}
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    try:
        user = int(user_id)
        user = User.objects.get(id = user_id)
        post_id = int(post_id)
        post = Post.objects.get(id = post_id)
    except:
        return HttpResponseForbidden()

    if not user == post.poster:
        return HttpResponseForbidden()

    error_title = False
    error_text = False
    error_title_toolong = False
    content = html2text.html2text( post.content )
    title = post.title
    group = post.group
    if request.method == 'POST':
        title = request.POST.get('title', '')
        if title == '':
            error_title = True
        elif len(title) > 40:
            error_title_toolong = True
        text = request.POST.get('text', '')
        content = text
        text = markdown.markdown(text) 
        if text == '':
            error_text = True

        if not error_title and not error_text and not error_title_toolong:
            Post.objects.filter(id = post_id).update(title=title, content=text, post_datetime=datetime.datetime.now())
            return HttpResponseRedirect('/group/post/' + str(post.id)) 

    render_result['error_title'] = error_title
    render_result['error_text'] = error_text
    render_result['error_title_toolong'] = error_title_toolong
    render_result['user'] = user
    render_result['title'] = title
    render_result['content'] = content
    render_result['group'] = group
    render_result['post'] = post
    render_result['username'] = get_username(request)

    return render_to_response('update_topic.html', render_result)


def download(request, post_id = None):

    if post_id:
        try:
            post_id = int(post_id)
            post = Post.objects.get(id = post_id)
        except:
            return HttpResponse(u'<h3 style="color:red">下载' + filename + u'失败！</h3>')

        attachment = post.attachment
        the_time = str(post.post_datetime)
        path = MEDIA_ROOT + 'upload_file/' + the_time[:4] + '/' + the_time[5:7] + '/' + the_time[8:10] + '/'
        filename = path + attachment

        try:
            fp = open(filename, 'rb')
            data = fp.read()
            fp.close()
        except:
            return HttpResponse(u'<h3 style="color:red">下载' + filename + u'失败！</h3>')
        response = HttpResponse(data, mimetype='application/octet-stream')

        fff, fext = os.path.splitext(attachment)
        fname = str(long(time.time()*1000000))[:-1] + fext
        print type(attachment)
        response['Content-Disposition'] = 'attachment; filename= %s ' % attachment.encode('utf8')
        return response
    
    return HttpResponseRedirect('/group/all_groups/')

def show_guideline(request):

    return render_to_response('guideline.html', {})


def test(request):
    return render_to_response('base.html', {})

    
def test_group(request):
    return render_to_response('group_base.html', {})



